import {
	IContext,
	IParam,
	computedNavData,
	deepCopy,
	getSessionStorage,
} from '@/core';
import { getCookie } from 'qx-util';
import { Ref } from 'vue';

/**
 * 处理编辑器导航参数
 *
 * @export
 * @param {Record<string, any>} props
 * @return {*}
 */
export function handleEditorNavParams(props: Record<string, any>) {
	const { localContext, localParam, data } = props;
	const { context, viewParams } = useContextParams(props);
	const navParams = {
		navContext: context.value,
		navViewParam: viewParams.value,
	};
	if (localContext && Object.keys(localContext).length > 0) {
		const _context = computedNavData(
			data,
			navParams.navContext,
			navParams.navViewParam,
			localContext
		);
		Object.assign(navParams.navContext, _context);
	}
	if (localParam && Object.keys(localParam).length > 0) {
		const _param = computedNavData(
			data,
			navParams.navContext,
			navParams.navViewParam,
			localParam
		);
		Object.assign(navParams.navViewParam, _param);
	}
	return navParams;
}

/**
 * 处理上下文参数
 *
 * @export
 * @param {Record<any, any>} props
 * @return {*}
 */
export function useContextParams(props: Record<any, any>) {
	const { context, viewParams } = props;
	// 维护上下文并监控其变化
	const _context: Ref<IContext> = ref({});
	watch(
		() => context,
		(newVal: any, oldVal: any) => {
			_context.value = deepCopy(newVal || {});
		},
		{
			immediate: true,
			deep: true,
		}
	);
	// 维护视图参数并监控其变化
	const _viewParams: Ref<IParam> = ref({});
	watch(
		() => viewParams,
		(newVal: any, oldVal: any) => {
			_viewParams.value = deepCopy(newVal || {});
		},
		{
			immediate: true,
			deep: true,
		}
	);
	return { context: _context, viewParams: _viewParams };
}

// 获取文件上传路径
export function getUploadUrl(): string {
	const { baseUrl, uploadFileUrl } = App.getProjectSetting();
	return baseUrl + uploadFileUrl;
}

//获取文件下载路径
export function getDownloadUrl(): string {
	const { baseUrl, exportFileUrl } = App.getProjectSetting();
	return baseUrl + exportFileUrl;
}

//获取文件请求头
export function getRequestingHeader(): IParam {
	const headers: IParam = {};
	if (App.getProjectSetting().saasMode) {
		const activeOrgData = getSessionStorage('activeOrgData');
		headers['srforgid'] = activeOrgData?.orgid;
		headers['srfsystemid'] = activeOrgData?.systemid;
	}
	if (getCookie('ibzuaa-token')) {
		headers['Authorization'] = `Bearer ${getCookie('ibzuaa-token')}`;
	} else {
		// 第三方应用打开免登
		if (sessionStorage.getItem('srftoken')) {
			const token = sessionStorage.getItem('srftoken');
			headers['Authorization'] = `Bearer ${token}`;
		}
	}
	return headers;
}
